# coding:utf-8
from typing import Union

from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QWidget, QHBoxLayout
from qfluentwidgets import BodyLabel, SimpleCardWidget, IconWidget, TransparentToolButton, FluentIcon as FIF, \
    FluentIconBase


class ProviderCard(SimpleCardWidget):
    removed = pyqtSignal(QWidget)
    edited = pyqtSignal(QWidget)  # 新增编辑信号

    def __init__(self, icon: Union[str, QIcon, FluentIconBase], title: str, parent=None):
        super().__init__(parent)
        self.horizontalLayout = QHBoxLayout(self)
        self.iconWidget = IconWidget(icon, self)
        self.bodyLabel = BodyLabel(title, self)
        self.editButton = TransparentToolButton(FIF.EDIT, self)  # 新增编辑按钮
        self.removeButton = TransparentToolButton(FIF.CLOSE, self)

        self.iconWidget.setFixedSize(40, 40)

        self.setObjectName('ProviderCard')
        self.horizontalLayout.setContentsMargins(20, 10, 10, 10)
        self.horizontalLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.bodyLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addStretch(1)
        self.horizontalLayout.addWidget(self.editButton, 0, Qt.AlignmentFlag.AlignRight)  # 添加编辑按钮到布局
        self.horizontalLayout.addWidget(self.removeButton, 0, Qt.AlignmentFlag.AlignRight)

        self.removeButton.clicked.connect(lambda: self.removed.emit(self))
        self.editButton.clicked.connect(lambda: self.edited.emit(self))  # 连接编辑按钮信号

        # 初始时隐藏编辑和删除按钮
        self.editButton.hide()
        self.removeButton.hide()

    def enterEvent(self, event):
        """鼠标进入事件，显示编辑和删除按钮"""
        self.editButton.show()
        self.removeButton.show()
        super().enterEvent(event)

    def leaveEvent(self, event):
        """鼠标离开事件，隐藏编辑和删除按钮"""
        self.editButton.hide()
        self.removeButton.hide()
        super().leaveEvent(event)

    def setText(self, text: str):
        """设置卡片标题"""
        self.bodyLabel.setText(text)
